package com.tc.zigbee.application;


import java.io.IOException;

import com.tc.gateway.ErrorListener;
import com.tc.gateway.GatewayEngine;
import com.tc.gateway.HomeApplication;
import com.tc.gateway.ProxyException;
import com.tc.gateway.tunnel.TunnelManager;
import com.tc.gateway.tunnel.TunnelServer;
import com.tc.serial.SerialFactory;
import com.tc.serial.SerialStream;
import com.tc.serial.WorkingConfig;

import com.tc.zigbee.entity.Endpoint;
import com.tc.zigbee.mt.Monitor;
import com.tc.zigbee.mt.MtCommand;
import com.tc.zigbee.mt.RequestQueue;
import com.tc.zigbee.mt.ZigbeeManager;
import com.tc.zigbee.mt.request.RequestFactory;


public class ZigbeeHomeApplication implements ErrorListener, HomeApplication{
	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#getGatewayEngine()
	 */
	public GatewayEngine getGatewayEngine() {
		return manager;
	}

	public ZigbeeHomeApplication() throws ProxyException, IOException {
		super();
		 manager = new ZigbeeManager();
		 stream = SerialFactory.getStream();
			if(stream == null)
				throw new ProxyException();
			if(WorkingConfig.mainController)
				tunnelServer = TunnelManager.getServer(stream.getOutputStream());
			monitor = new Monitor(stream, tunnelServer);
			
			 monitor.addListener(manager);


			 monitor.setErrorListener(this);
	}

	Monitor monitor;
	ZigbeeManager manager;
	TunnelServer tunnelServer;
	boolean started = false;
	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#getTunnelServer()
	 */
	public TunnelServer getTunnelServer() {
		return tunnelServer;
	}
	SerialStream stream;
	private ErrorListener listener;
	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#start()
	 */
	public void start() throws ProxyException, IOException{

		if(WorkingConfig.simulator)
			manager.createDummy();
	
		 monitor.start();
		Endpoint ep = manager.remoteControl;
		MtCommand r = RequestFactory.MtAfRegister(ep);
		RequestQueue.offer(r);
		r = RequestFactory.MtIEEEAddrRequest((short)0x00, (byte)0, (byte)1);
		RequestQueue.offer(r);
		started = true;
		

	}

	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#isStarted()
	 */
	public boolean isStarted() {
		return started;
	}

	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#stop()
	 */
	public void stop() {
		if(tunnelServer != null){
			tunnelServer.stop();
		}
		
		started = false;
	}

	/* (non-Javadoc)
	 * @see com.tc.zigbee.application.HomeApplication#onException(java.lang.Throwable)
	 */
	public void onException(Throwable e) {
		if(listener != null)
			listener.onException(e);
	
	}

	public void setErrorListener(ErrorListener ls) {
		listener = ls;
		
	}
}
